//
// Menu Demo
// a cocos2d example
// http://www.cocos2d-iphone.org
//


#import "MenuTest.h"
#import "GameScene.h"

#import "GameCenterLayer.h"


#import "SWListButton.h"
#import "SWList.h"
#import "SWListLayer.h"

enum {
	kTagMenu = 1,
	kTagMenu0 = 0,
	kTagMenu1 = 1,
};





#pragma mark -
#pragma mark MainMenu

@implementation Layer1
-(id) init
{
	if( (self=[super init])) {
		CGSize winSize=[[CCDirector sharedDirector] winSize];
		
        /*
		CCLabel * label=[CCLabel labelWithString:@"Linear Birds" 
										fontName:@"Marker Felt"
										fontSize:50];
		label.color=ccc3(0, 0, 0);
		label.position=ccp(winSize.width/2,winSize.height-30);
		[self addChild:label z:7 tag:0];
		*/
		
		[CCMenuItemFont setFontSize:30];
		[CCMenuItemFont setFontName: @"Courier New"];
        
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
        self.isTouchEnabled = YES;
#endif
		
		
		
		/*
		CCSprite * bg=[CCSprite spriteWithFile:@"menu-bg.jpg"];
		bg.position=ccp(winSize.width*3/2,winSize.height/2);
		//bg.color=ccc3(60, 60, 60);
		[self addChild: bg];
		*/
		
        NSString * str_pic_name=nil;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            str_pic_name=@"Background_doodle-hd.png";
        }
        else{
            str_pic_name=@"Background_doodle.png";
        }
        
		CCSprite * bg0=[CCSprite spriteWithFile:str_pic_name];  //Background_doodle.png
		bg0.anchorPoint=ccp(0,0);
		//bg.position=ccp(winSize.width/2,winSize.height/2);
		bg0.position=ccp(0,0);
		//bg.color=ccc3(100, 100, 100);
		[self addChild:bg0 z:0 tag:99];
		
        
        /*
        NSString * fish_name_plist=nil;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            fish_name_plist=@"gameEngineSpriteSheetDefault-hd.plist";
        }
        else{
            fish_name_plist=@"gameEngineSpriteSheetDefault.plist";
        }
        
        
        
        // Load the Texture Atlas sprite frames, this also loads the Texture with the same name.
        CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
        [frameCache addSpriteFramesWithFile:fish_name_plist];
        */
        
        
        
        NSString * str_bg_name=nil;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            str_bg_name=@"bush-hd.png";
        }
        else{
            str_bg_name=@"bush.png";
        }
        
		CCSprite * bg=[CCSprite spriteWithFile:str_bg_name];  //Background_doodle.png
        float scalX=winSize.width/(float)bg.contentSize.width;
		bg.anchorPoint=ccp(0,0);
        bg.scaleX=scalX;
		//bg.position=ccp(winSize.width/2,winSize.height/2);
		bg.position=ccp(0,0);
		//bg.color=ccc3(100, 100, 100);
		[self addChild:bg z:0 tag:99];
        
        
        /*
		CCSprite * bg=[CCSprite spriteWithSpriteFrameName:@"bush1.png"];  //bush1.png
		bg.anchorPoint=ccp(0,0);
		//bg.position=ccp(winSize.width/2,winSize.height/2);
		bg.position=ccp(0,0);
		//bg.color=ccc3(100, 100, 100);
		[self addChild:bg z:0 tag:100];
		
		
		CCSprite * bg2=[CCSprite spriteWithSpriteFrameName:@"bush2.png"];  //bush2.png
		bg2.anchorPoint=ccp(1,0);
		//bg.position=ccp(winSize.width/2,winSize.height/2);
		bg2.position=ccp(winSize.width,0);
		//bg.color=ccc3(100, 100, 100);
		[self addChild:bg2 z:0 tag:100];
		*/
		
		/*
		CCMoveTo *move=[CCMoveTo actionWithDuration:0.5 position:ccp(winSize.width/2,winSize.height/2)];
		CCSequence *seque=[CCSequence actions:move,nil];
		//CCEaseIn	* easeIn=[CCEaseIn actionWithAction:seque];////由慢变到及其快 
		//[bg runAction:easeIn];
		[bg runAction:seque];
		*/
		// Font Item
		
		//CCSprite *spriteNormal = [CCSprite spriteWithFile:@"menuitemsprite.png" rect:CGRectMake(0,23*2,115,23)];
		//CCSprite *spriteSelected = [CCSprite spriteWithFile:@"menuitemsprite.png" rect:CGRectMake(0,23*1,115,23)];
		//CCSprite *spriteDisabled = [CCSprite spriteWithFile:@"menuitemsprite.png" rect:CGRectMake(0,23*0,115,23)];
		//CCMenuItemSprite *item1 = [CCMenuItemSprite itemFromNormalSprite:spriteNormal selectedSprite:spriteSelected disabledSprite:spriteDisabled target:self selector:@selector(menuCallback:)];
		
		
		/*
		CCSprite *sprite1 = [CCSprite spriteWithFile:@"menu_begin.png"];
		CCMenuItemSprite *item1 = [CCMenuItemSprite itemFromNormalSprite:sprite1 
														  selectedSprite:sprite1 
														  disabledSprite:sprite1 target:self selector:@selector(menuStartCallback:)];
		*/
		CCMenuItem *item1 = [CCMenuItemImage itemFromNormalImage:@"menu_begin.png" selectedImage:@"menu_begin_high.png" target:self selector:@selector(menuStartCallback:)];
		
		// Image Item
		CCMenuItem *item2 = [CCMenuItemImage itemFromNormalImage:@"menu_setting.png" selectedImage:@"menu_setting_high.png" target:self selector:@selector(menuCallbackConfig:)];

        
        // Image Item
		CCMenuItem *item3 = [CCMenuItemImage itemFromNormalImage:@"menu_more.png" selectedImage:@"menu_setting_high.png" target:self selector:@selector(menuCallbackConfig:)];
        
        
        // Image Item
		CCMenuItem *item4 = [CCMenuItemImage itemFromNormalImage:@"menu_GC.png" selectedImage:@"menu_setting_high.png" target:self selector:@selector(menuCallbackConfig:)];
        
        
		// Label Item (LabelAtlas)
		/*
		CCLabelAtlas *labelAtlas = [CCLabelAtlas labelAtlasWithString:@"0123456789" charMapFile:@"fps_images.png" itemWidth:16 itemHeight:24 startCharMap:'.'];
		CCMenuItemLabel *item3 = [CCMenuItemLabel itemWithLabel:labelAtlas target:self selector:@selector(menuCallbackDisabled:)];
		item3.disabledColor = ccc3(32,32,64);
		item3.color = ccc3(200,200,255);
		*/


		

		
		// Font Item
		//CCMenuItemFont *item6 = [CCMenuItemFont itemFromString: @"Quit" target:self selector:@selector(onQuit:)];
		
		id color_action = [CCTintBy actionWithDuration:0.5f red:0 green:-25 blue:-255];
		id color_back = [color_action reverse];
		id seq = [CCSequence actions:color_action, color_back, nil];
		[item1 runAction:[CCRepeatForever actionWithAction:seq]];

		CCMenu *menu = [CCMenu menuWithItems: item1, item2, nil];
		//[menu alignItemsHorizontally];
		[menu alignItemsVertically];	
        
        /*
        [menu alignItemsInColumns:
        //[menu alignItemsInRows:
		 [NSNumber numberWithUnsignedInt:2],
		 [NSNumber numberWithUnsignedInt:2],
         //[NSNumber numberWithUnsignedInt:1],
         //[NSNumber numberWithUnsignedInt:1],
         nil
		 ]; 
        */
        
		// elastic effect
		CGSize s = [[CCDirector sharedDirector] winSize];
		int i=0;
		for( CCNode *child in [menu children] ) {
			
			if(1 == i)
			{
				child.position=ccp(child.position.x,child.position.y-30);
			}
			
			CGPoint dstPoint = child.position;
			int offset = s.width/2 + 50;
			if( i % 2 == 0)
				offset = -offset;
			child.position = ccp( dstPoint.x + offset, dstPoint.y);
			[child runAction: 
			 [CCEaseElasticOut actionWithAction:
			  [CCMoveBy actionWithDuration:2 position:ccp(dstPoint.x - offset,0)]
										 period: 0.35f]
			];
			i++;
		}

		//disabledItem = [item3 retain];
		//disabledItem.isEnabled = NO;
		menu.position=ccp(menu.position.x,menu.position.y+50);
		[self addChild: menu];
        
        
        //[self addOpenFeintButton];
        
        [self addSWButton];
        [self addGCButton];
        
        
        //ad-bg
        CCSprite * ad_bg=[CCSprite spriteWithFile:@"game-center-ad-bg.png"];
        ad_bg.position=ccp(s.width/2,ad_bg.contentSize.height/2);
        [self addChild:ad_bg z:0 tag:1001];
        ad_bg.visible=false;
	}

	return self;
}

-(void) menuCallbackConfig:(id) sender
{
	[GameMusicSetting playEffect:@"button.caf"];
	
	
	
	//[(CCLayerMultiplex*)parent_ switchTo:3];
	CCScene *scene = [CCScene node];
	
	CCLayer *layer = [Layer4 node];
	[scene addChild: layer z:1];
	
	//[[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
	[[CCDirector sharedDirector] replaceScene: scene];
	
	//[[CCDirector sharedDirector] pushScene: 
	//			[CCTransitionMoveInR transitionWithDuration:0.5f scene:scene]];
}

-(void) menuStartCallback: (id) sender
{
	[GameMusicSetting playEffect:@"button.caf"];

	
	//[(CCLayerMultiplex*)parent_ switchTo:1];
	[[CCDirector sharedDirector] pushScene: [GameScene scene]];
	

}


-(void) dealloc
{
	[disabledItem release];
	[super dealloc];
}

-(void) menuCallback: (id) sender
{
	//[(CCLayerMultiplex*)parent_ switchTo:1];
}




-(void) menuCallbackDisabled:(id) sender {

}

-(void) menuCallbackEnable:(id) sender {
	disabledItem.isEnabled = ~disabledItem.isEnabled;
}

-(void) menuCallback2: (id) sender
{
	//[(CCLayerMultiplex*)parent_ switchTo:2];
}

-(void) onQuit: (id) sender
{
	CC_DIRECTOR_END();	
}




#pragma mark game center 
-(void)gotoGameCenter:(id)sender
{
    //[director_ pushScene: [gameCenterLayer scene]]; 
    
    
    // [[CCDirector sharedDirector] pushScene:[gameCenterLayer scene]];
    
    
    //[OpenFeint launchDashboard];
    
    
    /*
     GameKitHelper *gkHelper = [GameKitHelper sharedGameKitHelper];
     //gkHelper.delegate = self;
     //[gkHelper authenticateLocalPlayer];
     [gkHelper showLeaderboard];
     
     */
    
    
    ///push scene,pop scene
	CCScene *scene = [CCScene node];
	
	CCLayer *layer = [GameCenterLayer node];
	[scene addChild:layer z:1];
	
	//[[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
	[[CCDirector sharedDirector] pushScene:scene];
}

-(void)addOpenFeintButton
{
    

    
    ////////////////////////
	CCSprite * tmp=[CCSprite spriteWithFile:@"game_center_logo30.png"];
	
	CGSize size = [[CCDirector sharedDirector] winSize];
    
	
    
	CCMenuItemImage * help=[CCMenuItemImage itemFromNormalImage:@"game_center_logo30.png" 
												  selectedImage:@"game_center_logo30.png" 
														 target:self selector:@selector(gotoGameCenter:)];
	
    /*
     tmp.scale=36/(float)tmp.contentSize.width;
     CCMenuItemSprite * help=[CCMenuItemSprite itemFromNormalSprite:(CCNode<CCRGBAProtocol>*)tmp selectedSprite:(CCNode<CCRGBAProtocol>*)tmp 
     target:self selector:@selector(gotoGameCenter:)];
     */
	CCMenu * menu=[CCMenu menuWithItems:help,nil];
	menu.position=ccp(tmp.contentSize.width/2*4,tmp.contentSize.height/2+3);
	[self addChild:menu z:4 tag:10210];
	
}

#pragma mark GC button
-(void)addGCButton
{
    GameKitHelper *gkHelper = [GameKitHelper sharedGameKitHelper];
    gkHelper.delegate = self;
    [gkHelper authenticateLocalPlayer];
    ////////////////////////////////////
    
    CCSprite * tmp=[CCSprite spriteWithFile:@"menu_GC.png"];
    
    CGSize size=[[CCDirector sharedDirector] winSize];
    //[self addSWListButton:self point:ccp(size.width/2,100)];
    
    
    CCMenuItem *item4 = [CCMenuItemImage itemFromNormalImage:@"menu_GC.png" selectedImage:@"menu_setting_high.png" target:self selector:@selector(gotoGameCenter:)];
    
    
    CCMenu * menu=[CCMenu menuWithItems:item4,nil];
    menu.position=ccp(size.width/2-size.width/6,size.height/3);
    [self addChild:menu z:4];
}





#pragma mark addSWButton
-(void)addSWButton
{
    CGSize size=[[CCDirector sharedDirector] winSize];
    [self addSWListButton:self point:ccp(size.width/2+size.width/6,size.height/3)];
}


-(void)gotoSWList:(id)sender
{

    
    ///数据获取线程还未结束，则不能进入
    SWList * aSWList=[SWList sharedInstance];
    if ([aSWList getThreadOverFlag] == false) {
        myNSLog(@"aSWList getThreadOverFlag false\n");
        return;
    }
    
    
    [GameMusicSetting playButtonClickEffect];
    
    
    
    
    ///push scene,pop scene
	CCScene *scene = [CCScene node];
	
	SWListLayer *layer = [SWListLayer node];
    [layer setPageIndex:0];
    [layer updateDisplay];
	[scene addChild:layer z:1];
	
	//[[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
	[[CCDirector sharedDirector] pushScene:scene];
}

-(void)addSWListButton:(id)sender point:(CGPoint)position
{
	CCSprite * tmp=[CCSprite spriteWithFile:@"menu_more.png"];
	
	CGSize size = [[CCDirector sharedDirector] winSize];
    
	
    
	CCMenuItemImage * help=[CCMenuItemImage itemFromNormalImage:@"menu_more.png" 
												  selectedImage:@"menu_more.png" 
														 target:self selector:@selector(gotoSWList:)];
	
    /*
     tmp.scale=36/(float)tmp.contentSize.width;
     CCMenuItemSprite * help=[CCMenuItemSprite itemFromNormalSprite:(CCNode<CCRGBAProtocol>*)tmp selectedSprite:(CCNode<CCRGBAProtocol>*)tmp 
     target:self selector:@selector(gotoGameCenter:)];
     */
	CCMenu * menu=[CCMenu menuWithItems:help,nil];
	//menu.position=ccp(tmp.contentSize.width/2,tmp.contentSize.height/6-2);
    CGPoint newPoint=ccp(position.x+tmp.contentSize.width/2, position.y);
    //menu.anchorPoint=ccp(0.0, 0.0);  //左下角定位
    menu.position=position;
    
	//[self addChild:menu z:4];
	[sender addChild:menu z:10];	
}





//////////////////////////////////////////////ad begin
#pragma Mark adMobBanner
- (void)onEnter
{
    
    static int count=0;
    count ++;
    
	[super onEnter];
	
    //首次启动不显示广告
    if (count >= 2) {
        adController = [[AdViewController alloc] initWithMasterView:[[CCDirector sharedDirector] openGLView]];
        [adController setDelegate:self];
        
   
    }
    

	
}

- (void)onExit
{
	//Completely remove the controller
	[adController setDelegate:nil];
    
    if (adController != nil) {
        [adController release];
        adController = nil;
    }

	
	[super onExit];
}

- (void)adController:(AdViewController*)controller didLoadiAd:(id)iadBanner;
{
	//Do something when the ad loads, like moving objects.
    
    
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=true;
}

- (void)adController:(AdViewController*)controller didFailedToRecieveiAd:(id)iadBanner;
{
	//Do something when the ad fails to load, like moving objects.;
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=false;
}

- (void)adController:(AdViewController*)controller didLoadAdMobAd:(ADBannerView*)adMobBanner;
{
	//Do something when the ad loads, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=true;
}

- (void)adController:(AdViewController*)controller didFailedToRecieveAdMobAd:(ADBannerView*)adMobBanner;
{
	//Do something when the ad fails to load, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=false;
}

//////////////////////////////ad end


/////-----------------------------
#pragma mark GameKitHelper delegate methods
-(void) onLocalPlayerAuthenticationChanged
{
    GKLocalPlayer* localPlayer = [GKLocalPlayer localPlayer];
    CCLOG(@"LocalPlayer isAuthenticated changed to: %@", localPlayer.authenticated ? @"YES" : @"NO");
    
    if (localPlayer.authenticated)
    {
        GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper];
        [gkHelper getLocalPlayerFriends];
        //[gkHelper resetAchievements];
    }   
}

-(void) onFriendListReceived:(NSArray*)friends
{
    CCLOG(@"onFriendListReceived: %@", [friends description]);
    GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper];
    [gkHelper getPlayerInfo:friends];
}
-(void) onPlayerInfoReceived:(NSArray*)players
{
    CCLOG(@"onPlayerInfoReceived: %@", [players description]);
    
    
}
-(void) onScoresSubmitted:(bool)success
{
    CCLOG(@"onScoresSubmitted: %@", success ? @"YES" : @"NO");
}
-(void) onScoresReceived:(NSArray*)scores
{
    CCLOG(@"onScoresReceived: %@", [scores description]);
    GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper];
    [gkHelper showAchievements];
}
-(void) onAchievementReported:(GKAchievement*)achievement
{
    CCLOG(@"onAchievementReported: %@", achievement);
}
-(void) onAchievementsLoaded:(NSDictionary*)achievements
{
    CCLOG(@"onLocalPlayerAchievementsLoaded: %@", [achievements description]);
}
-(void) onResetAchievements:(bool)success
{
    CCLOG(@"onResetAchievements: %@", success ? @"YES" : @"NO");
}
-(void) onLeaderboardViewDismissed
{
    CCLOG(@"onLeaderboardViewDismissed");
    
    GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper];
    [gkHelper retrieveTopTenAllTimeGlobalScores];
}
-(void) onAchievementsViewDismissed
{
    CCLOG(@"onAchievementsViewDismissed");
}
-(void) onReceivedMatchmakingActivity:(NSInteger)activity
{
    CCLOG(@"receivedMatchmakingActivity: %i", activity);
}
-(void) onMatchFound:(GKMatch*)match
{
    CCLOG(@"onMatchFound: %@", match);
}
-(void) onPlayersAddedToMatch:(bool)success
{
    CCLOG(@"onPlayersAddedToMatch: %@", success ? @"YES" : @"NO");
}
-(void) onMatchmakingViewDismissed
{
    CCLOG(@"onMatchmakingViewDismissed");
}
-(void) onMatchmakingViewError
{
    CCLOG(@"onMatchmakingViewError");
}
-(void) onPlayerConnected:(NSString*)playerID
{
    CCLOG(@"onPlayerConnected: %@", playerID);
}
-(void) onPlayerDisconnected:(NSString*)playerID
{
    CCLOG(@"onPlayerDisconnected: %@", playerID);
}
-(void) onStartMatch
{
    CCLOG(@"onStartMatch");
}
-(void) onReceivedData:(NSData*)data fromPlayer:(NSString*)playerID
{
    CCLOG(@"onReceivedData: %@ fromPlayer: %@", data, playerID);
}







@end

#pragma mark -
#pragma mark StartMenu

@implementation Layer2

-(void) alignMenusH
{
	for(int i=0;i<2;i++) {
		CCMenu *menu = (CCMenu*)[self getChildByTag:100+i];
		menu.position = centeredMenu;
		if(i==0) {
			// TIP: if no padding, padding = 5
			[menu alignItemsHorizontally];			
			CGPoint p = menu.position;
			menu.position = ccpAdd(p, ccp(0,30));
			
		} else {
			// TIP: but padding is configurable
			[menu alignItemsHorizontallyWithPadding:40];
			CGPoint p = menu.position;
			menu.position = ccpSub(p, ccp(0,30));
		}		
	}
}

-(void) alignMenusV
{
	for(int i=0;i<2;i++) {
		CCMenu *menu = (CCMenu*)[self getChildByTag:100+i];
		menu.position = centeredMenu;
		if(i==0) {
			// TIP: if no padding, padding = 5
			[menu alignItemsVertically];			
			CGPoint p = menu.position;
			menu.position = ccpAdd(p, ccp(100,0));			
		} else {
			// TIP: but padding is configurable
			[menu alignItemsVerticallyWithPadding:40];	
			CGPoint p = menu.position;
			menu.position = ccpSub(p, ccp(100,0));
		}		
	}
}

-(id) init
{
	if( (self=[super init]) ) {
			
	}

	return self;
}

// Testing issue #1018 and #1021
-(void) onEnter
{	
	[super onEnter];

	// remove previously added children
	[self removeAllChildrenWithCleanup:YES];
	
	for( int i=0;i < 2;i++ ) {
		CCMenuItemImage *item1 = [CCMenuItemImage itemFromNormalImage:@"btn-play-normal.png" selectedImage:@"btn-play-selected.png" target:self selector:@selector(menuCallbackBack:)];
		CCMenuItemImage *item2 = [CCMenuItemImage itemFromNormalImage:@"btn-highscores-normal.png" selectedImage:@"btn-highscores-selected.png" target:self selector:@selector(menuCallbackOpacity:)];
		CCMenuItemImage *item3 = [CCMenuItemImage itemFromNormalImage:@"btn-about-normal.png" selectedImage:@"btn-about-selected.png" target:self selector:@selector(menuCallbackAlign:)];
		
		item1.scaleX = 1.5f;
		item2.scaleY = 0.5f;
		item3.scaleX = 0.5f;
		
		CCMenu *menu = [CCMenu menuWithItems:item1, item2, item3, nil];
		
		menu.tag = kTagMenu;
		
		[self addChild:menu z:0 tag:100+i];
		centeredMenu = menu.position;
	}
	
	alignedH = YES;
	[self alignMenusH];
}

-(void) dealloc
{
	[super dealloc];
}

-(void) menuCallbackBack: (id) sender
{
	//[(CCLayerMultiplex*)parent_ switchTo:0];
}

-(void) menuCallbackOpacity: (id) sender
{
	CCMenu *menu = (CCMenu*) [sender parent];
	GLubyte opacity = [menu opacity];
	if( opacity == 128 )
		[menu setOpacity: 255];
	else
		[menu setOpacity: 128];	
}
-(void) menuCallbackAlign: (id) sender
{
	alignedH = ! alignedH;
	
	if( alignedH )
		[self alignMenusH];
	else
		[self alignMenusV];
}

@end

#pragma mark -
#pragma mark SendScores

@implementation Layer3
-(id) init
{
	if( (self=[super init]) ) {
		[CCMenuItemFont setFontName: @"Marker Felt"];
		[CCMenuItemFont setFontSize:28];

		CCLabelAtlas *label = [CCLabelAtlas labelWithString:@"Enable AtlasItem" fntFile:@"bitmapFontTest3.fnt"];
		CCMenuItemLabel *item1 = [CCMenuItemLabel itemWithLabel:label target:self selector:@selector(menuCallback2:)];
		CCMenuItemFont *item2 = [CCMenuItemFont itemFromString: @"--- Go Back ---" target:self selector:@selector(menuCallback:)];
		
		CCSprite *spriteNormal = [CCSprite spriteWithFile:@"menuitemsprite.png" rect:CGRectMake(0,23*2,115,23)];
		CCSprite *spriteSelected = [CCSprite spriteWithFile:@"menuitemsprite.png" rect:CGRectMake(0,23*1,115,23)];
		CCSprite *spriteDisabled = [CCSprite spriteWithFile:@"menuitemsprite.png" rect:CGRectMake(0,23*0,115,23)];
		
		CCMenuItemSprite *item3 = [CCMenuItemSprite itemFromNormalSprite:spriteNormal selectedSprite:spriteSelected disabledSprite:spriteDisabled target:self selector:@selector(menuCallback3:)];
		disabledItem = item3;
		disabledItem.isEnabled = NO;
		
		CCMenu *menu = [CCMenu menuWithItems: item1, item2, item3, nil];	
		menu.position = ccp(0,0);
		
		CGSize s = [[CCDirector sharedDirector] winSize];
		
		item1.position = ccp(s.width/2 - 150, s.height/2);
		item2.position = ccp(s.width/2 - 200, s.height/2);
		item3.position = ccp(s.width/2, s.height/2 - 100);
		
		id jump = [CCJumpBy actionWithDuration:3 position:ccp(400,0) height:50 jumps:4];
		[item2 runAction: [CCRepeatForever actionWithAction:
					 [CCSequence actions: jump, [jump reverse], nil]
									   ]
		 ];
		id spin1 = [CCRotateBy actionWithDuration:3 angle:360];
		id spin2 = [[spin1 copy] autorelease];
		id spin3 = [[spin1 copy] autorelease];
		
		[item1 runAction: [CCRepeatForever actionWithAction:spin1]];
		[item2 runAction: [CCRepeatForever actionWithAction:spin2]];
		[item3 runAction: [CCRepeatForever actionWithAction:spin3]];
		
		[self addChild: menu];
	}
	
	return self;
}

- (void) dealloc
{
	[super dealloc];
}

-(void) menuCallback: (id) sender
{
	//[(CCLayerMultiplex*)parent_ switchTo:0];
}

-(void) menuCallback2: (id) sender
{
	NSLog(@"Label clicked. Toogling Sprite");
	disabledItem.isEnabled = ~disabledItem.isEnabled;
	[disabledItem stopAllActions];
}
-(void) menuCallback3:(id) sender
{
	NSLog(@"MenuItemSprite clicked");
}

@end

#pragma mark the configur  layer
@implementation Layer4
-(id) init
{
	if( (self = [super init] ) ) {

		
		/*
		 CGSize winSize=[[CCDirector sharedDirector] winSize];
		 
		 CCSprite * bg=[CCSprite spriteWithFile:@"welcome101.png"];
		 bg.position=ccp(winSize.width*3/2,winSize.height/2);
		 //bg.color=ccc3(60, 60, 60);
		 [self addChild: bg];
		 
		 CCMoveTo *move=[CCMoveTo actionWithDuration:0.5 position:ccp(winSize.width/2,winSize.height/2)];
		 CCSequence *seque=[CCSequence actions:move,nil];
		 //CCEaseIn	* easeIn=[CCEaseIn actionWithAction:seque];////由慢变到及其快 
		 //[bg runAction:easeIn];
		 [bg runAction:seque];
		 */
		
		CGSize winSize=[[CCDirector sharedDirector] winSize];
		
        
        NSString * str_bg_name=nil;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            str_bg_name=@"Background_doodle-hd.png";
        }
        else{
            str_bg_name=@"Background_doodle.png";
        }
        
        
		CCSprite * bg0=[CCSprite spriteWithFile:str_bg_name];  //Background_doodle.png
		bg0.anchorPoint=ccp(0,0);
		//bg.position=ccp(winSize.width/2,winSize.height/2);
		bg0.position=ccp(0,0);
		//bg.color=ccc3(100, 100, 100);
		[self addChild:bg0 z:0 tag:99];
		
        /*
        //NSString * str_bg_name=nil;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            str_bg_name=@"bush1-hd.png";
        }
        else{
            str_bg_name=@"bush1.png";
        }
        
		CCSprite * bg=[CCSprite spriteWithFile:str_bg_name];  //bush1.png
		bg.anchorPoint=ccp(0,0);
		//bg.position=ccp(winSize.width/2,winSize.height/2);
		bg.position=ccp(0,0);
		//bg.color=ccc3(100, 100, 100);
		[self addChild:bg z:0 tag:100];
		
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            str_bg_name=@"bush2-hd.png";
        }
        else{
            str_bg_name=@"bush2.png";
        }
        
		CCSprite * bg2=[CCSprite spriteWithFile:str_bg_name];  //bush2.png
		bg2.anchorPoint=ccp(1,0);
		//bg.position=ccp(winSize.width/2,winSize.height/2);
		bg2.position=ccp(winSize.width,0);
		//bg.color=ccc3(100, 100, 100);
		[self addChild:bg2 z:0 tag:100];
		*/
        
        NSString * str_bg2_name=nil;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            str_bg2_name=@"bush-hd.png";
        }
        else{
            str_bg2_name=@"bush.png";
        }
        
		CCSprite * bg=[CCSprite spriteWithFile:str_bg2_name];  //Background_doodle.png
        float scalX=winSize.width/(float)bg.contentSize.width;
		bg.anchorPoint=ccp(0,0);
        bg.scaleX=scalX;
		//bg.position=ccp(winSize.width/2,winSize.height/2);
		bg.position=ccp(0,0);
		//bg.color=ccc3(100, 100, 100);
		[self addChild:bg z:0 tag:99];
        
		/*
		//CGSize winSize=[[CCDirector sharedDirector] winSize];
		CCMoveTo *move=[CCMoveTo actionWithDuration:0.5 position:ccp(winSize.width/2,winSize.height/2)];
		CCSequence *seque=[CCSequence actions:move,nil];
		//CCEaseIn	* easeIn=[CCEaseIn actionWithAction:seque];////由慢变到及其快 
		//[bg runAction:easeIn];
		//CCSprite *bg=[self getChildByTag:100];
		[bg runAction:seque];
		*/
		
		
		//CCColorLayer * layer = [[CCColorLayer alloc] initWithColor:ccc4(0, 0, 0, 150)];//看看这个函数的文档
		//[self addChild:layer];
		
		[CCMenuItemFont setFontName: @"American Typewriter"];
		[CCMenuItemFont setFontSize:18];
		CCMenuItemFont *title1 = [CCMenuItemFont itemFromString: @"Sound"];
		[title1 setIsEnabled:NO];
		title1.color=ccc3(0, 0, 255);
		
		[CCMenuItemFont setFontName: @"Marker Felt"];
		[CCMenuItemFont setFontSize:34];
		CCMenuItemToggle *item1 = [CCMenuItemToggle itemWithTarget:self selector:@selector(menuSoundCallback:) items:
								 [CCMenuItemFont itemFromString: @"Off"],
								 [CCMenuItemFont itemFromString: @"On"],
								 nil];
		item1.color=ccc3(255, 0, 0);
		item1.selectedIndex=[GameMusicSetting getIsSoundOn];
		
		[CCMenuItemFont setFontName: @"American Typewriter"];
		[CCMenuItemFont setFontSize:18];
		CCMenuItemFont *title2 = [CCMenuItemFont itemFromString: @"Music"];
		[title2 setIsEnabled:NO];
		title2.color=ccc3(0, 0, 255);
		
		[CCMenuItemFont setFontName: @"Marker Felt"];
		[CCMenuItemFont setFontSize:34];
		CCMenuItemToggle *item2 = [CCMenuItemToggle itemWithTarget:self selector:@selector(menuMusicCallback:) items:
								 [CCMenuItemFont itemFromString: @"Off"],
								 [CCMenuItemFont itemFromString: @"On"],
								 nil];
		item2.color=ccc3(255, 0, 0);
		item2.selectedIndex=[GameMusicSetting getIsMusicOn];
		
		[CCMenuItemFont setFontName: @"American Typewriter"];
		[CCMenuItemFont setFontSize:18];
		CCMenuItemFont *title0 = [CCMenuItemFont itemFromString: @"Vibration"];  //震动
		[title0 setIsEnabled:NO];
		title0.color=ccc3(0, 0, 255);
		
		[CCMenuItemFont setFontName: @"Marker Felt"];
		[CCMenuItemFont setFontSize:34];
		CCMenuItemToggle *item0 = [CCMenuItemToggle itemWithTarget:self selector:@selector(menuVibrateCallback:) items:
								   [CCMenuItemFont itemFromString: @"Off"],
								   [CCMenuItemFont itemFromString: @"On"],
								   nil];
		item0.color=ccc3(255, 0, 0);
		item0.selectedIndex=[GameMusicSetting getIsVibrateOn];
		
		[CCMenuItemFont setFontName: @"American Typewriter"];
		[CCMenuItemFont setFontSize:18];
		CCMenuItemFont *title3 = [CCMenuItemFont itemFromString: @"mode"];
		[title3 setIsEnabled:NO];
		title3.color=ccc3(0, 0, 255);
		
		[CCMenuItemFont setFontName: @"Marker Felt"];
		[CCMenuItemFont setFontSize:34];
		CCMenuItemToggle *item3 = [CCMenuItemToggle itemWithTarget:self selector:@selector(menuModeCallback:) items:
								 [CCMenuItemFont itemFromString: @"Easy"],
								 [CCMenuItemFont itemFromString: @"Normal"],
								 [CCMenuItemFont itemFromString: @"Hard"],
								 nil];
		item3.color=ccc3(255, 0, 0);
		item3.selectedIndex=[GameMusicSetting getGameLevelSeeting];
		
		[CCMenuItemFont setFontName: @"American Typewriter"];
		[CCMenuItemFont setFontSize:18];
		CCMenuItemFont *title4 = [CCMenuItemFont itemFromString: @"Orientation"];
		[title4 setIsEnabled:NO];
		[CCMenuItemFont setFontName: @"Marker Felt"];
		[CCMenuItemFont setFontSize:34];
		CCMenuItemToggle *item4 = [CCMenuItemToggle itemWithTarget:self selector:@selector(menuCallback:) items:
								 [CCMenuItemFont itemFromString: @"Off"], nil];
		
		NSArray *more_items = [NSArray arrayWithObjects:
								 [CCMenuItemFont itemFromString: @"33%"],
								 [CCMenuItemFont itemFromString: @"66%"],
								 [CCMenuItemFont itemFromString: @"100%"],
								 nil];
		// TIP: you can manipulate the items like any other NSMutableArray
		[item4.subItems addObjectsFromArray: more_items];
		
		// you can change the one of the items by doing this
		item4.selectedIndex = 2;
		
		[CCMenuItemFont setFontName: @"Marker Felt"];
		[CCMenuItemFont setFontSize:34];
		
		//CCLabelBMFont *label = [CCLabelAtlas labelWithString:@"go back" fntFile:@"bitmapFontTest3.fnt"];
		//CCMenuItemLabel *back = [CCMenuItemLabel itemWithLabel:label target:self selector:@selector(backCallback:)];
		
		// Image Item
		CCSprite * tmpSprite=[CCSprite spriteWithFile:@"menu_quit.png"];

		CCMenuItem *back = [CCMenuItemImage 
							itemFromNormalImage:@"menu_quit.png" 
							selectedImage:@"menu_quit_high.png" 
							target:self 
							selector:@selector(backCallback:)];
		CCMenu *menuBack = [CCMenu menuWithItems:
							back,nil];
		[menuBack alignItemsHorizontally];
		menuBack.position=ccp(winSize.width-tmpSprite.contentSize.width/2,tmpSprite.contentSize.height/2); ///右下角
		[self addChild: menuBack];
		
		CCMenu *menu = [CCMenu menuWithItems:
					  title1, title2,title0,
					  item1, item2,item0,
					  title3, //title4,
					  item3, //item4,
					  /*back,*/ nil]; // 9 items.
		[menu alignItemsInColumns:
		 [NSNumber numberWithUnsignedInt:3],
		 [NSNumber numberWithUnsignedInt:3],
		 [NSNumber numberWithUnsignedInt:1],
		 [NSNumber numberWithUnsignedInt:1],
		 /*[NSNumber numberWithUnsignedInt:1],*/
		 nil
		]; // 2 + 2 + 2 + 2 + 1 = total count of 9.

		
		
		// elastic effect
		CGSize s = [[CCDirector sharedDirector] winSize];
		int i=0;
		int commonX;
		for( CCNode *child in [menu children] ) {
			
			///修正某些菜单的位置
			if(i==0||i==3)
			{
				child.position=ccp(child.position.x+s.width/10,child.position.y);
			}
			else if(i==2||i==5)
			{
				child.position=ccp(child.position.x-s.width/10,child.position.y);
				
			}
			else if(1==i)
			{
				commonX=child.position.x;
			}
			else if(6==i || 7==i)
			{
				child.position=ccp(commonX,child.position.y);
				//child.position=ccp(0,child.position.y);
			}
			


			
			CGPoint dstPoint = child.position;

			int offset =s.width/10 + 0;
			if( i % 2 == 0){
				offset = -offset;
			}
			child.position = ccp( dstPoint.x + offset, dstPoint.y);
			[child runAction: 
			 [CCEaseElasticOut actionWithAction:
			  [CCMoveBy actionWithDuration:2 position:ccp(dstPoint.x - offset,0)]
										 period: 0.35f]
			 ];
			
			

			
			i++;
		}
		
		
		[self addChild: menu];
		
		
        //[self addSWButton];
        
        
        //ad-bg
        CCSprite * ad_bg=[CCSprite spriteWithFile:@"game-center-ad-bg.png"];
        ad_bg.position=ccp(s.width/2,ad_bg.contentSize.height/2);
        [self addChild:ad_bg z:0 tag:1001];
        ad_bg.visible=false;
        
        

	}
	
	return self;
}

- (void) dealloc
{
	[super dealloc];
}




-(void) menuSoundCallback: (id) sender
{
	NSLog(@"menuSoundCallback selected item: %@ index:%u", [sender selectedItem], (unsigned int) [sender selectedIndex] );
	
	bool IsSoundOn=[GameMusicSetting getIsSoundOn];
	IsSoundOn=!IsSoundOn;
	[GameMusicSetting setIsSoundOn:IsSoundOn];
	
	[GameMusicSetting playEffect:@"button.caf"];
}


-(void) menuMusicCallback: (id) sender
{
	NSLog(@"menuMusicCallback selected item: %@ index:%u", [sender selectedItem], (unsigned int) [sender selectedIndex] );
	
	[GameMusicSetting playEffect:@"button.caf"];

	bool IsMusicOn=[GameMusicSetting getIsMusicOn];
	IsMusicOn=!IsMusicOn;
	[GameMusicSetting setIsMusicOn:IsMusicOn];
    
    [GameMusicSetting playBackgroundMusic:@"xmas.mp3"];
}



-(void) menuVibrateCallback: (id) sender
{
		NSLog(@"menuVibrateCallback selected item: %@ index:%u", [sender selectedItem], (unsigned int) [sender selectedIndex] );
	
	[GameMusicSetting playEffect:@"button.caf"];
	
	bool isVibrateOn=[GameMusicSetting getIsVibrateOn];
	isVibrateOn=!isVibrateOn;
	[GameMusicSetting setIsVibrateOn:isVibrateOn];
}


-(void) menuModeCallback: (id) sender
{
	NSLog(@"selected item: %@ index:%u", [sender selectedItem], (unsigned int) [sender selectedIndex] );
	
	int index=(unsigned int) [sender selectedIndex]; //对应0 easy，1 normal，2 hard 
	[GameMusicSetting setGameLevel:index];
	
	
	[GameMusicSetting playEffect:@"button.caf"];
}

-(void) menuCallback: (id) sender
{
	NSLog(@"selected item: %@ index:%u", [sender selectedItem], (unsigned int) [sender selectedIndex] );
}

-(void) backCallback: (id) sender
{
	//[(CCLayerMultiplex*)parent_ switchTo:0];
	//[[CCDirector sharedDirector] popScene ]; //[CCTransitionMoveInR transitionWithDuration:0.5f scene:scene]
	
	CCScene *scene = [CCScene node];
	
	CCLayer *layer = [Layer1 node];
	[scene addChild: layer z:1];
	
	//[[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
	//[[CCDirector sharedDirector] pushScene: scene];
	
	[[CCDirector sharedDirector] replaceScene: 
	 [CCMoveInLTransition transitionWithDuration:0.5f scene:scene]];
	
	
	[GameMusicSetting playEffect:@"button.caf"];
}



//////////////////////////////////////////////////ad begin
#pragma Mark adMobBanner
- (void)onEnter
{
	[super onEnter];
	
	adController = [[AdViewController alloc] initWithMasterView:[[CCDirector sharedDirector] openGLView]];
	[adController setDelegate:self];
	
}

- (void)onExit
{
	//Completely remove the controller
	[adController setDelegate:nil];
	[adController release];
	adController = nil;
	
	[super onExit];
}

- (void)adController:(AdViewController*)controller didLoadiAd:(id)iadBanner;
{
	//Do something when the ad loads, like moving objects.
    
    
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=true;
}

- (void)adController:(AdViewController*)controller didFailedToRecieveiAd:(id)iadBanner;
{
	//Do something when the ad fails to load, like moving objects.;
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=false;
}

- (void)adController:(AdViewController*)controller didLoadAdMobAd:(ADBannerView*)adMobBanner;
{
	//Do something when the ad loads, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=true;
}

- (void)adController:(AdViewController*)controller didFailedToRecieveAdMobAd:(ADBannerView*)adMobBanner;
{
	//Do something when the ad fails to load, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=false;
}

//////////////////////////////ad end


@end



